package com.ymt.bpm.job;

import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.PBpdSeq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class SeqResetJob {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao mDao;

    @Scheduled(cron = "0 0 0 * * ? ")
    public void resetBpdSeq() {
        if (log.isDebugEnabled()) {
            log.debug("Running resetBpdSeq job");
        }
        Calendar now = Calendar.getInstance();
        List<PBpdSeq> batchToUpdate = new ArrayList<PBpdSeq>();
        List<PBpdSeq> seqs = null;
        int start = 0;
        Map<String, Object> paramMap = new HashMap<String, Object>();
        do {
            paramMap.put("offset", start);
            paramMap.put("limit", 10);
            seqs = mDao.selectList(Mapper.PBpdSeqMapper, "selectBatch", paramMap);
            for (PBpdSeq seq : seqs) {
                //检查是否到了seq最大值
                if (seq.getPattern().toUpperCase().indexOf("SEQ")>=0) {
                    String seqLen = seq.getPattern().substring(seq.getPattern().indexOf("{SEQ")+4);
                    seqLen = seqLen.substring(0, seqLen.indexOf("}"));
                    Long seqLength = new Double(Math.pow(10, Integer.parseInt(seqLen))).longValue() -1L;
                    if (seqLength.intValue()==seq.getCurrentValue()) {  //达到最大值
                        seq.setCurrentValue(1);
                        batchToUpdate.add(seq);
                    }
                }
                //检查是否按日月年重置
                if (seq.getPattern().toUpperCase().indexOf("DD")>=0 && seq.getCurrentValue()>1) {    //reset by day
                    seq.setCurrentValue(1);
                    batchToUpdate.add(seq);
                } else if (seq.getPattern().toUpperCase().indexOf("MM")>=0 && seq.getCurrentValue()>1
                        && now.get(Calendar.DAY_OF_MONTH)==1) { //reset by month
                    seq.setCurrentValue(1);
                    batchToUpdate.add(seq);
                } else if (seq.getPattern().toUpperCase().indexOf("YYYY")>=0 && seq.getCurrentValue()>1
                        && now.get(Calendar.DAY_OF_YEAR)==1) { //reset by year
                    seq.setCurrentValue(1);
                    batchToUpdate.add(seq);
                }
            }
            if (seqs!=null && seqs.size()>0) {
                start += seqs.size();
            }
        } while (seqs!=null && seqs.size()==10);
        int rs = mDao.batchUpdate(Mapper.PBpdSeqMapper, "updateByPrimaryKeySelective", batchToUpdate);
        if (log.isDebugEnabled()) {
            log.debug("Reset sequences of bpd num: "+rs);
        }
    }

}
